<template>
  <div class="lookupTestDetailMainSearch table-page-search-wrapper">
    <a-form-model ref="formComp" :model="queryParams" style="flex:1 0 0;" layout="horizontal">
      <div class="lookupTestDetailMainSearchBox" v-show="false">
        <div>
          <a-spin :spinning="loaddingTestLists">
            <common-select
              :options="testOptions"
              :default-value="queryParams.taskId"
              :allow-clear="false"
              :show-search="true"
              @changeoption="changeTask"></common-select>
          </a-spin>
        </div>
        <div>
          <!-- 取消任务   -->
          <auth-button
            :auth="strategyPerms[versionType][upgradeTriggerType].fotaSjcl.createTest"
            :disabled="stopStarting"
            type="danger"
            style="margin-left:10px"
            @click="handelCancel"
            :loading="canceling"
            v-if="activeTestTaskInfo.status !== 16 && activeTestTaskInfo.status !== 17 && activeTestTaskInfo.status !== 18">{{
              $t('cancelTask')
            }}</auth-button>
        </div>
      </div>
      <a-row :gutter="[24,16]">
         <a-col :md="11" v-if="!upgradeTaskId">
          <a-spin :spinning="loaddingTestLists">
            <common-select
              :loading="false"
              :options="testOptions"
              :default-value="queryParams.taskId"
              :allow-clear="false"
              :show-search="true"
              @changeoption="changeTask"></common-select>
          </a-spin>
          <!-- 车辆 -->
        </a-col>
          <a-col :md="5">
            <detail-item :span="24" :label-width="30" label="车辆" textAlign="right">
              <a-input v-model="vin" placeholder="请输入vin码"/>
            </detail-item>
          </a-col>
          <a-col :md="6">
            <detail-item :span="24" :label-width="60" label="升级结果" textAlign="right">
              <!-- 升级结果 -->
              <a-select
                allow-clear
                v-model="status"
                :placeholder="$t('pleaseSelect')"
                style="width:100%;margin-bottom: 0"
              >
                <a-select-option v-for="(item, index) in taskVehicleStatusDictCode" :key="index" :value="item.value">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </detail-item>
          </a-col>
        <a-col :md="13" v-if="activeTestTaskInfo.status">
          <div class="searchBtns">
          <auth-button type="primary" @click="handleSearch" style="margin-right:0">
            <i class="iconfont icon-chazhao"></i>
            {{ $t('inquiry') }}
          </auth-button>
          <question-mark-tip
          :tip-title="'输入查询条件后，才能进行查询重置操作'"
          :popupContainer="getPopupContainer">
          </question-mark-tip>
          <auth-button @click="clearCondition" style="margin-left:10px">
            <i class="iconfont icon-qingkong"></i>
            {{ $t('clear') }}
          </auth-button>
<!--          <auth-button-->
<!--            style="margin-left:10px"-->
<!--            v-if="taskInfo.channel === 1"-->
<!--            :auth="strategyPerms[versionType][upgradeTriggerType].fotaSjcl.createTest"-->
<!--            :disabled="activeTestTaskInfo.status == 16 || activeTestTaskInfo.status == 17 || activeTestTaskInfo.status == 18 || canceling"-->
<!--            @click="handleStopStart(activeTestTaskInfo.status === 13)"-->
<!--            :loading="stopStarting">{{-->
<!--              $t(activeTestTaskInfo.status === 13 ? 'recoveryTask' : 'pauseTask')-->
<!--            }}</auth-button>-->
          <!-- 取消任务   -->
          <auth-button
            :auth="strategyPerms[versionType][upgradeTriggerType].fotaSjcl.createTest"
            :disabled="taskInfo.fromGcy || activeTestTaskInfo.status == 16 || activeTestTaskInfo.status == 17 || activeTestTaskInfo.status == 18 || stopStarting"
            type="danger"
            style="margin-left:10px"
            @click="handelCancel"
            :loading="canceling"
          >{{
            $t('cancelTask')
          }}</auth-button>
          <!-- 重发指令 -->
          <auth-button
            style="margin-left:10px"
            v-if="(taskType == 2 || taskType == 8) && taskInfo.channel === 1"
            :auth="strategyPerms[versionType][upgradeTriggerType].fotaSjcl.createTest"
            :disabled="!(taskStatus == 12 || resending)"
            :loading="resending"
            @click="resendCommand(activeTestTaskInfo.status === 13)"
          >{{
            $t('resendCommand')
          }}</auth-button>
          </div>
        </a-col>
      </a-row>
    </a-form-model>
  </div>
</template>
<script>
import detailItem from '@comp/EditItem'
import FilterBoxCollection from '@/components/SelfComponents/FilterBoxCollection'
import CarModelSelect from '@/views/components/CarModelSelect.vue'
import PartSoftSelect from '@/views/components/PartSoftSelect'
import TaskSelect from '@/views/components/TaskSelect'
import CommonSelect from '@/components/SelfComponents/CommonSelect.vue'
import { mapGetters, mapState } from 'vuex'
import { strategyPerms } from '@/config/permission/index'
import AuthButton from '@/components/AuthButton'
import QuestionMarkTip from '@/views/components/QuestionMarkTip'
const initTaskInfo = {
  id: '',
  status: '',
  name: ''
}
export default {
  components: {
    FilterBoxCollection,
    CarModelSelect,
    PartSoftSelect,
    TaskSelect,
    CommonSelect,
    AuthButton,
    detailItem,
    QuestionMarkTip
  },
  props: {
    upgradeTaskId: {
      type: String,
      default: ''
    },
    strategyId: {
      type: String,
      default: ''
    },
    versionType: {
      type: String,
      default: ''
    },
    upgradeTriggerType: {
      type: String,
      default: ''
    },
    exporting: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    ...mapState({
      taskVehicleStatusDictCode: (state) => state.dict.taskVehicleStatusDictCode,
      queryParams: (state) => state.strategy.taskVehicleQueryParams
    }),
    ...mapGetters(['drawerOpenTime'])
  },
  data () {
    return {
      strategyPerms,
      loaddingTestLists: false,
      testOptions: [],
      activeTestTaskInfo: { ...initTaskInfo },
      stopStarting: false,
      canceling: false,
      resending: false,
      taskStatus: -1,
      taskType: -1,
      taskInfo: {},
      vin:'',
      status:undefined
    }
  },
  watch: {
    drawerOpenTime: {
      handler () {
        this.getTestData()
      },
      immediate: true
    },
    'queryParams.taskId' : function (val) {
      this.getTaskStatus()
    }
  },
  // created () {
  //   console.log('created')
  //   this.getTaskStatus()
  // },
  updated () {
    // this.getTaskStatus()
  },
  methods: {
    getPopupContainer () {
      return document.body
    },
    handleSearch(){
      this.$emit('sendSearchKey', this.vin,this.status)
    },
    clearCondition(){
      this.vin='',
      this.status=undefined
      this.$emit('sendSearchKey', this.vin,this.status)
    },
    // 获取任务状态和类型
    getTaskStatus () {
      const vm = this
      vm.$api.getTaskInfor({ id: vm.queryParams.taskId }).then((res) => {
        vm.taskStatus = res.data.status
        vm.taskType = res.data.type
        vm.taskInfo = res.data
      })
    },
    changeTask (val) {
      this.queryParams.taskId = val
      this.getActiveTestTaskInfo(val)
      this.$emit('search', val)
    },
    // 重发命令
    resendCommand () {
      const vm = this
      this.$confirm({
        title: vm.$t('resendCommand'),
        content: vm.$t('resendCommandTip'),
        class: 'confirmStyle',
        width: 378,
        onOk () {
          vm.resending = true
          const queryParam = {
            taskId: vm.queryParams.taskId
          }
          vm.$api.resendCommandTask(queryParam).then(() => {
            vm.$message.success(vm.$t('successfullyOperation'))
            vm.$emit('search', 'justUpdate')
          }).finally(() => {
            vm.resending = false
          })
        },
        onCancel () { }
      })
    },
    // 获取某策略下的所有测试数据
    getTestData () {
      this.testOptions = []
      this.loaddingTestLists = true
      this.queryParams.taskId = ''
      this.$store.dispatch('getTaskSelectData', {
        type: [9, 10, 8],
        strategyId: this.strategyId
      }).then((res) => {
        this.testOptions = res.data.map(item => {
          let { name } = item
          if (item.type === 10) {
            name += '[' + this.$t('cycleTestTask') + ']'
          }
          return {
            name,
            id: item.id,
            status: item.status
          }
        })
        if (this.upgradeTaskId) {
          this.changeTask(this.upgradeTaskId)
        }else if(res.data[0] && res.data[0].id){
          this.changeTask(res.data[0].id)
        }
      }).finally(() => {
        this.loaddingTestLists = false
      })
    },
    getActiveTestTaskInfo (taskId) {
      const obj = this.testOptions.find(item => item.id === taskId)
      if (obj) {
        this.activeTestTaskInfo = {
          id: obj.id,
          name: obj.name,
          status: obj.status
        }
      } else {
        this.activeTestTaskInfo = {
          ...initTaskInfo
        }
      }
    },
    // 挂起或者恢复任务
    handleStopStart (enabled) {
      const vm = this
      this.$confirm({
        title: vm.$t('systemTip'),
        // eslint-disable-next-line max-len
        content: enabled ? vm.$t('continueTaskTip').replace('__TaskName__', vm.activeTestTaskInfo.name) : vm.$t('pauseTaskTip').replace('__TaskName__', vm.activeTestTaskInfo.name),
        onOk () {
          vm.stopStarting = true
          vm.$api.stopOrStart({ ids: [vm.activeTestTaskInfo.id], enabled }, vm.versionType).then(() => {
            vm.activeTestTaskInfo.status = enabled ? 12 : 13
            vm.$message.success(vm.$t('successfullyOperation'))
          }).finally(() => {
            vm.stopStarting = false
          })
        },
        onCancel () {}
      })
    },

    // 取消任务
    handelCancel () {
      const vm = this
      this.$confirm({
        title: vm.$t('cancelTask'),
        content: vm.$t('newCancelTaskTip').replace('__TaskName__', vm.activeTestTaskInfo.name),
        class: 'confirmStyle',
        width: 378,
        onOk () {
          vm.canceling = true
          vm.$api.cancelTask({ ids: [vm.activeTestTaskInfo.id] }, vm.versionType).then(() => {
            vm.activeTestTaskInfo.status = 16
            vm.$message.success(vm.$t('successfullyOperation'))
          }).finally(() => {
            vm.canceling = false
          })
        },
        onCancel () { }
      })
    }
  }
}
</script>
<style lang="less">
.lookupTestDetailMainSearch {
  .disabledAuthButtonWrap {
    margin-right: 0;
  }
}
</style>
